package com.pig4cloud.pig.demo.Util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * redis工具类
 * Created by caoxuel on 2020/10/23 18:53
 * @author caoxuel
 */
public final class RedisUtil {

    public static void set(String key, Object object, RedisTemplate<String, String> redisTemplate) {
        //参数检查
        if (StringUtils.isEmpty(key) || object == null || redisTemplate == null) {
            return;
        }
        ObjectMapper om = new ObjectMapper();
        //将对象转为json字符串
        String objectData = null;
        try {
            objectData = om.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //将数据存到redis
        redisTemplate.boundValueOps(key).set(objectData);
    }

    public static <T> T get(String key, Class<T> type, RedisTemplate<String, String> redisTemplate) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        //将json字符串转为对象
        String jsonObject = redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(jsonObject)){
            return null;
        }
        return om.readValue(jsonObject, type);
    }
}
